﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication3
{
    public partial class DriverPaymentForm : Form
    {
        //    private String connString = Program.ConnStr;
       public   driverpaymentbean  driverpaymentbean = null;
       DriverPaymentTransaction drivertransaction = null;
        private bool nonNumberEntered = false;
        
        
        public DriverPaymentForm()
        {
            InitializeComponent();
            drivertransaction = new DriverPaymentTransaction();
            lbldriverinvoice.Text = drivertransaction.newinvoiceget();

            jobcomboboxload();
            

            
        }
        public DriverPaymentForm(String JobCode)
        {
            InitializeComponent();
            cmbjobcode.SelectedText = JobCode;
        }
    /*  public DriverPaymentForm(BillDatabean billdatabean)
        {

            InitializeComponent();

            cmbjobcode.SelectedText = billdatabean.JobCode;

            cmbjobcode.Enabled = false;
            btnLater.Enabled = true;
            btnCancel.Enabled = false;


        }
     */
        
        public DriverPaymentForm( driverpaymentbean  driverpaymentbean)
        {
            InitializeComponent();
          
            fillForm( driverpaymentbean);
            showallPaymentbyjobcode();
            revievetotal();
            
            
            

        }

        private void DriverPaymentForm_Load(object sender, EventArgs e)
        {
            jobcomboboxload();
           
        }

        private void button1_Click(object sender, EventArgs e)
        {


            addaction();



        }



        /// <summary>
        /// ADD A NEW PAYMENT
        /// </summary>
        public void addaction()
        {
            if (validationcontrol())
            {
                 driverpaymentbean = null;

                 driverpaymentbean = insertdatapayment();

                if ( driverpaymentbean != null)
                {
                    insertintDBpaydata( driverpaymentbean);
                    MessageBox.Show("sucess");
                   
                    clearcontrols();
                    this.Close();
                }
            }
        }


        /// <summary>
        /// INSERT DATA INTO DATABEAN FOR INSERTING
        /// </summary>
        /// <returns></returns>
        public  driverpaymentbean insertdatapayment()

        {

             driverpaymentbean = new  driverpaymentbean();
             driverpaymentbean.Jobcode = cmbjobcode.Text;
             driverpaymentbean.Drivinvcode = lbldriverinvoice.Text;
             driverpaymentbean.Acceptorname = txtAcceptorName.Text;
             driverpaymentbean.Amount = float.Parse(mxtAmount.Text.ToString());
             driverpaymentbean.Postdate = dtppostdate.Value;
             driverpaymentbean.Description1 = rtxtDescription.Text;
             driverpaymentbean.Vehicleno = txtvehicleno.Text;
            if (rbtcheque.Checked)
            {
                 driverpaymentbean.Chequeno = txtchequeno.Text;
                 driverpaymentbean.Bankname = txtBankName.Text;
                 driverpaymentbean.Chequedate = dtpchequedate.Value;
                 driverpaymentbean.Chequereleasedate = dtpreleasingdate.Value;

                 driverpaymentbean.Iscashselected = false;
                 driverpaymentbean.Ischequeselected = true;
            }
            else if (rbtCash.Checked)
            {
                 driverpaymentbean.Chequeno = "";
                 driverpaymentbean.Bankname = "";

                 driverpaymentbean.Iscashselected = true;
                 driverpaymentbean.Ischequeselected = false;

            }



            return  driverpaymentbean;
        }


        /// <summary>
        /// INSERT DATA INTO DATABASE
        /// </summary>
        /// <param name=" CompanyPaymentDatabean"></param>
        public void insertintDBpaydata( driverpaymentbean  driverpaymentbean)
        {



            try
            {

                OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(Program.ConnStr);
                oleDbConnection1.Open();

                OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO driverpaymentmastertable (jobcode ,drivername,amount,chequeno,chequereleasedate,postdate,chequedate,ischeque,iscash,description,vehicleno, dinvcode) Values ('" + driverpaymentbean.Jobcode.ToString() + "','" + driverpaymentbean.Acceptorname.ToString() + "'," + driverpaymentbean.Amount + ",'" + driverpaymentbean.Chequeno + "','" + driverpaymentbean.Chequereleasedate + "','" + driverpaymentbean.Postdate + "','" + driverpaymentbean.Chequedate + "'," + driverpaymentbean.Ischequeselected + "," + driverpaymentbean.Iscashselected + ",'" + driverpaymentbean.Description1 + "','" + driverpaymentbean.Vehicleno + "', '" + driverpaymentbean.Drivinvcode + "') ", oleDbConnection1);
                oleDbCommand1.CommandType = CommandType.Text;
                oleDbCommand1.ExecuteNonQuery();

                oleDbConnection1.Close();
                clearcontrols();
            }
            catch (Exception e)
            {

                MessageBox.Show("Exception at Database close any Access Database program and restart" + e);
                Console.WriteLine("Error", e);
            }






        }


        public void clearcontrols()
        {
            txtAcceptorName.Text = "";
            txtBankName.Text = "";
            txtchequeno.Text = "";
           cmbjobcode.SelectedText = "";
            mxtAmount.Text = "";
            btnCancel.Enabled = true;
            lblagreeamount.Text = "0.0";
            lblbalance.Text = "0.0";
            lbldriveramount.Text = "0.0";
            lblpaid.Text = "0.0";


        }

        /// <summary>
        /// VALIDATES ALL CONTROL
        /// </summary>
        /// <returns></returns>
        public Boolean validationcontrol()
        {
            Boolean sucess = true;
            
            if (lbldriverinvoice.Text.Trim() == null || lbldriverinvoice.Text.Trim() == "" || lbldriverinvoice.Text.Trim() == "####")
            {
                MessageBox.Show("NO customer data found");
                sucess = false;
                this.Close();
            }
            if (cmbjobcode.Text.Trim() == null || cmbjobcode.Text.Trim() == "")
            {
                MessageBox.Show(cmbjobcode.SelectedValue.ToString());
                cmbjobcode.Focus();
                cmbjobcode.Text = "";
                sucess = false;
                lblstatus.Text = "Enter jobcode";
            }
            else if (txtAcceptorName.Text.Trim() == null || txtAcceptorName.Text.Trim() == "")
            {

                txtAcceptorName.Focus();
                txtAcceptorName.Text = "";
                sucess = false;
                lblstatus.Text = "EnterAcepptor Name";
            }
            else if (txtvehicleno.Text.Trim() == null || txtvehicleno.Text.Trim() == "")
            {

                txtvehicleno.Focus();
                txtvehicleno.Text = "";
                sucess = false;
                lblstatus.Text = "Enter vehicle No";
            }
            else if (mxtAmount.Text.Trim() == null || mxtAmount.Text.Trim() == "")
            {

                mxtAmount.Focus();
                mxtAmount.Text = "";
                sucess = false;
                lblstatus.Text = "Enter Acceptor Name";
            }
            else if (rbtcheque.Checked)
            {
                if (txtchequeno.Text.Trim() == null || txtchequeno.Text.Trim() == "")
                {

                    txtchequeno.Focus();
                    txtchequeno.Text = "";
                    sucess = false;
                    lblstatus.Text = "Enter Cheque No";
                }
                if (txtBankName.Text.Trim() == null || txtBankName.Text.Trim() == "")
                {

                    txtBankName.Focus();
                    txtBankName.Text = "";
                    sucess = false;
                    lblstatus.Text = "Enter Bank Name";
                }


            }




            return sucess;
        }



        private void button2_Click(object sender, EventArgs e)
        {
            this.Dispose();
            
        }

   

        /// <summary>
        /// enables and disables textboxes according to selected mode of payment
        /// if cash all bank details ui is disabled
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void rbtcheque_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtcheque.Checked)
            {
                txtBankName.Enabled = true;
                txtchequeno.Enabled = true;
                dtpchequedate.Enabled = true;
                dtpreleasingdate.Enabled = true;

            }
            else
            {
                txtBankName.Enabled = false;
                txtchequeno.Enabled = false;
                dtpchequedate.Enabled = false;
                dtpreleasingdate.Enabled = false;
            }
        }

        private void mxtAmount_KeyDown(object sender, KeyEventArgs e)
        {
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace.
                    if (e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }

                }
            }
        }
        private void mxtAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (nonNumberEntered == true)
            {

                e.Handled = true;
                lblstatus.Text = "Enter Amount Correctly";

            }

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            clearcontrols();
        }


        //fill the dform with data taken fronm the database
        // here the usercan edit the Data
        public void fillForm( driverpaymentbean  driverpaymentbean)
        {
            cmbjobcode.Text =  driverpaymentbean.Jobcode;
            cmbjobcode.Enabled = false;
            
            
            txtAcceptorName.Text =  driverpaymentbean.Acceptorname;

           
            txtvehicleno.Text =  driverpaymentbean.Vehicleno;
           
        }

        private void btnLater_Click(object sender, EventArgs e)
        {

            txtAcceptorName.Text = "-";
            txtBankName.Text = "-";
            txtchequeno.Text = "-";
            txtvehicleno.Text = "-";
            mxtAmount.Text = "0";
            addaction();
            btnCancel.Enabled = true;


        }
        /// <summary>
        /// TO SEARCH AND GET A JOBCODE
        /// GOES TO JOBCODESEARCHFORM
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnsearch_Click(object sender, EventArgs e)
        {
            SearcJobCode searchjobCode = new SearcJobCode();
            searchjobCode.Show();
            this.Close();
            this.Dispose();
        }
     

        private void btnCancel_Click(object sender, EventArgs e)
        {
           
            this.Close();
        }
  

      

       /// <summary>
       /// load jobcodecombobox
       /// </summary>
       public void jobcomboboxload()
       {

           OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(Program.ConnStr);
           oleDbConnection1.Open();
           OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobcode from  jobcodemastertable", oleDbConnection1);
           OleDbDataReader reader = oleDbCommand1.ExecuteReader();
           DataTable dt = new DataTable();
         
           dt.Columns.Add("jobpk", typeof(int));
           dt.Columns.Add("jobcode", typeof(string));
           dt.Load(reader);
           cmbjobcode.ValueMember = "jobpk";
           cmbjobcode.DisplayMember = "jobcode";
           cmbjobcode.DataSource = dt.DefaultView;

           oleDbConnection1.Close();

       }

       /// <summary>
       /// load vehicle combobox asper given jobcode
       /// </summary>
       public void Vehiclenocomboboxload()
       {

           try
           {
               OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(Program.ConnStr);
               oleDbConnection1.Open();

               OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("SELECT driverassignmastertable.drivername, driverassignmastertable.vehicleno, driverassignmastertable.amount, driverassignmastertable.driverpk FROM driverassignmastertable WHERE(((driverassignmastertable.jobcodepk)= @jobcodepk))", oleDbConnection1);
               oleDbCommand1.Parameters.AddWithValue("@jobcodepk", cmbjobcode.SelectedValue);
               OleDbDataReader reader = oleDbCommand1.ExecuteReader();
               DataTable dt = new DataTable();


               dt.Columns.Add("vehicleno", typeof(string));
               dt.Columns.Add("drivername", typeof(string));
               dt.Columns.Add("amount", typeof(int));
               dt.Columns.Add("driverpk", typeof(int));
               dt.Load(reader);
               if (dt.Rows.Count == 0)
               {
                   MessageBox.Show("No vehicle Assigned to this Invoice");

                   cmbVehicleno.DataSource = null;
                   txtvehicleno.Text = "";
                   lblagreeamount.Text = "";
                   txtAcceptorName.Text = "";
               }
               else
               {

                   cmbVehicleno.ValueMember = "driverpk";
                   cmbVehicleno.DisplayMember = "vehicleno";


                   cmbVehicleno.DataSource = dt.DefaultView;
                   txtvehicleno.Text = cmbVehicleno.Text;
                   lblagreeamount.Text = dt.Rows[0]["amount"].ToString();
                   txtAcceptorName.Text = dt.Rows[0]["drivername"].ToString();


               }

               oleDbConnection1.Close();
           }
           catch (Exception exp)
           {
               
              MessageBox.Show("Error  Loading combobox>>>>at driverpaymentform.Vehiclenocomboboxload()"+exp+"");
              this.Close();
           }

       }

      

       private void cmbjobcode_SelectedIndexChanged(object sender, EventArgs e)
       {
           
         Vehiclenocomboboxload();
         showallPaymentbyjobcode();
       revievetotal();
       addtotalpaid();
         
       }

       private void cmbVehicleno_SelectedIndexChanged(object sender, EventArgs e)
       {

       }









       /// <summary>
       /// DISPLAY ALL PAYMENT AGAINST JOBCODE
       /// </summary>
       public void showallPaymentbyjobcode()
       {
           try
           {



               String query = "Select jobcode ,vehicleno,amount,dinvcode,postdate,description,ischeque,iscash from driverpaymentmastertable  where jobcode Like '" + cmbjobcode.Text + "'  Order by postdate";
               OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, Program.ConnStr);
               DataSet ds = new DataSet();
               dAdapter.Fill(ds, "tblpayview");
               tblpaymentview.DataSource = ds.Tables["tblpayview"].DefaultView;
             
               if (ds.Tables.Count <= 0)
               {
                   lblstatus.Text = "No Payment Details Present";
                   clearcontrols();
               }

           }
           catch (Exception)
           {
               MessageBox.Show("The application had met with some errors please restart  the application :\n error:closer MSAccess files>>at driverpaymentform.showallPaymentbyjobcode() ");

           }


       }


       /// <summary>
       ///ADD ALL PAID AMOUNT AND DISPLAY IN A LABEL
       ///add all previously paid amount and gives the total paid
       /// </summary>
       public void addtotalpaid()
       {
        
           try
           {
               double sum = 0;
               double balance = 0;
               double amountpayable = double.Parse(lbldriveramount.Text.ToString());
              
               int count = tblpaymentview.RowCount;
               if (count != 0)
               {

                   for (int i = 0; i < count; i++)
                   {

                       if (tblpaymentview.Rows[i].Cells[3].Value != null)
                       {
                           sum = sum + double.Parse(tblpaymentview.Rows[i].Cells[2].Value.ToString());
                       }
                   }
                   balance = amountpayable - sum;
           

               
                   lblpaid.Text = sum.ToString();
                   lblbalance.Text = balance.ToString();

               }
           }
           catch (Exception exp)
           {

               MessageBox.Show("Error  Calculating totalpaid >>>>at driverpaymentform. addtotalpaid()" + exp + "");
               this.Close();
           }






       }


       /// <summary>
       /// get the total driverpayment to be done against the Invoice
       /// it includes all drivers total amount
       /// </summary>

       public void revievetotal()
       {


           try
           {
               int driveramounttotal = 0;

               String query = "Select * from driverassignmastertable where jobcode= '" + cmbjobcode.Text + "' ";
               OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, Program.ConnStr);
               DataSet ds = new DataSet();
               dAdapter.Fill(ds, "driverassignm");

               if (ds.Tables[0].Rows.Count == 0)
               {
                   MessageBox.Show("No Amount  Confirmed against this Invoice");
                   clearcontrols();
               }
               else
               {
                   driveramounttotal = 0;
                   for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                   {
                       driveramounttotal = driveramounttotal + int.Parse(ds.Tables[0].Rows[i][6].ToString());

                   }
                   lbldriveramount.Text = driveramounttotal.ToString();
               }
           }
           catch (Exception exp)
           {

               MessageBox.Show("Error  Calculating total>>>>at driverpaymentform.revievetotal()" + exp + "");
               this.Close();
           }


       }







    }
}
